<?php

namespace app\common\lib;

use Doctrine\Common\Annotations\PhpParser;
use think\Exception;
use think\facade\Filesystem;

class Toutiao
{
    static private $_instance;

    /**
     * @return mixed
     */
    static public function getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    protected array $config = [];
    public function __construct(array $config = [])
    {
        if (empty($config)) {
            $this->config = [
                "AppID" => "tt3c034abea33d958101",
                "AppSecret" => "46a4a48f2879e9bf3ea4d8877dc6c5997cc231ed",
            ];
        } else {
            $this->config = $config;
        }
    }

    /**
     * 获取抖音开发token
     * @return mixed
     * @throws Exception
     */
    public function getAccessToken(){
        $data='{
          "appid": "'.$this->config['AppID'].'",
          "secret": "'.$this->config['AppSecret'].'",
          "grant_type": "client_credential"
        }';
        $result = $this->header_url("https://developer.toutiao.com/api/apps/v2/token",$data);
        return json_decode($result,true);
    }

    /**
     * 退款
     * @param $data
     * @return mixed
     * @throws Exception
     */
    public function refund_order($data){
        $paramdata =[
            'app_id'=>$this->config['AppID'],
            'out_order_no'=>$data['ordersn'],
            'out_refund_no'=>$data['out_refund_no'],
            'reason'=>$data['reason'],
            'refund_amount'=>intval($data['money']*100)
        ];
        $sign= $this->sign($paramdata);
        $jsondata ='{
              "app_id": "'.$this->config['AppID'].'",
              "out_order_no": "'.$data['ordersn'].'",
              "out_refund_no": "'.$data['out_refund_no'].'",
              "reason":"'.$data['reason'].'",
              "refund_amount": '.intval($data['money']*100).',              
              "sign": "'.$sign.'"                    
            }';
        $result = $this->header_url("https://developer.toutiao.com/api/apps/ecpay/v1/create_refund",$jsondata);
        return json_decode($result,true);
    }

    /**
     * 查询退款
     * @param $data
     * @return mixed
     * @throws Exception
     */
    public function query_refund($data){
        $paramdata =[
            'out_refund_no'=>$data['out_refund_no'],
            'app_id'=>$this->config['AppID']
        ];
        $sign= $this->sign($paramdata);
        $jsondata ='{
          "out_refund_no": "'.$data['out_refund_no'].'",
          "app_id": "'.$this->config['AppID'].'",
          "sign": "'.$sign.'"
        }';
        $result =$this->header_url('https://developer.toutiao.com/api/apps/ecpay/v1/query_refund',$jsondata);
        return json_decode($result,true);
    }


    /**
     * 创建订单
     * @param $data
     * @return mixed
     * @throws Exception
     */
    public function create_order($data){
        $paramdata =[
            'app_id'=>$this->config['AppID'],
            'out_order_no'=>$data['orderno'],
            'total_amount'=>intval($data['payprice']*100),
            'subject'=>"抖音商品",
            'body'=>"搜划算",
            'valid_time'=>600,
            'notify_url'=>"https://toutiao.jixuantiant.com/api/v1.login/notify"
        ];
        $sign= $this->sign($paramdata);
        $jsondata ='{
              "app_id": "'.$this->config['AppID'].'",
              "out_order_no": "'.$data['orderno'].'",
              "total_amount": '.intval($data['payprice']*100).',
              "subject": "抖音商品",
              "body": "搜划算",
              "valid_time": 600,
              "sign": "'.$sign.'",
              "notify_url": "https://toutiao.jixuantiant.com/api/v1.login/notify"
            }';
        $result = $this->header_url("https://developer.toutiao.com/api/apps/ecpay/v1/create_order",$jsondata);
        return json_decode($result,true);
    }

    protected function strToUtf8($str){
        $encode = mb_detect_encoding($str, array("ASCII",'UTF-8',"GB2312","GBK",'BIG5'));
        if($encode == 'UTF-8'){
            return $str;
        }else{
            return mb_convert_encoding($str, 'UTF-8', $encode);
        }
    }

    protected function sign($map) {
        $rList = array();
        foreach($map as $k =>$v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
                continue;
            $value = trim(strval($v));
            $len = strlen($value);
            if ($len > 1 && substr($value, 0,1)=="\"" && substr($value,$len, $len-1)=="\"")
                $value = substr($value,1, $len-1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            array_push($rList, $value);
        }
        array_push($rList, "XPMbsfmD3LHLmS0kp7XYESmYGtu6pzp2QS4qr4TQ");
        sort($rList, 2);
        return md5(implode('&', $rList));
    }

    /**
     * 生成抖音二维码
     * @param $access_token
     * @param $appname
     * @param $path
     * @return mixed
     * @throws Exception
     */
    public function createQRCode($access_token,$appname,$path,$id){

        $data='{
          "access_token": "'.$access_token.'",
          "appname": "'.$appname.'",
          "path": "'.$path.'",     
          "width": 430,
          "line_color": { "r": 0, "g": 0, "b": 0 },        
          "background": { "r": 255, "g": 255, "b": 255 },        
          "set_icon": true
        }';
        $result = $this->header_url("https://developer.toutiao.com/api/apps/qrcode",$data);
        file_put_contents(public_path('upload/doorcode').$id.'.png',$result);
        return  request()->domain(). '/upload/doorcode/'.$id.'.png';
    }



    /**
     * 登录凭证openid
     * @param $code
     * @param $anonymousCode
     * @return mixed
     * @throws Exception
     */
    public function code2Session($code,$anonymousCode){
        $data='{
              "appid": "'.$this->config['AppID'].'",
              "secret": "'.$this->config['AppSecret'].'",
              "anonymous_code": "'.$anonymousCode.'",
              "code": "'.$code.'"
            }';
        $result = $this->header_url("https://developer.toutiao.com/api/apps/v2/jscode2session",$data);
        return json_decode($result,true);
    }

    /**
     * @param string $url
     * @param array $data
     * @return bool|string
     * @throws Exception
     */
    private function header_url(string $url = "", string $jsonStr)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=UTF-8',
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $response;
    }


}